package com.youlin.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.youlin.dto.BaseResDto;
import com.youlin.dto.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class MySessionExpiredStrategy implements SessionInformationExpiredStrategy {

    Logger logger = LoggerFactory.getLogger(MySessionExpiredStrategy.class);

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        HttpServletResponse response = event.getResponse();
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(new ObjectMapper().writeValueAsString(new BaseResDto<>(Status.RELOGIN)));
            out.flush();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (out != null) out.close();
        }
    }
}